function openDialog() {
    var dialogBorder = document.getElementsByClassName("md-upload")[0];
    dialogBorder.style.display = "block";
}
//取消上传函数ok
function cancelUpload() {
    document.getElementsByClassName("md-upload")[0].style.display = "none";
    document.getElementsByName("file")[0].value = "";
    document.getElementsByClassName("fileAddress")[0].value = "";

}
//点击tag-top按钮
function tagTop() {
    document.getElementsByClassName("comment-msg")[0].style.display = "none";
}
//点击插入函数
function insert() {
    if (document.getElementsByClassName("fileAddress")[0].value != "") {
        var fileAddress = document.getElementsByClassName("fileAddress")[0].value;
        var originaltext = document.getElementById("md-area1").value;
        document.getElementById("md-area1").value = originaltext + "![](" + fileAddress + ")";
        cancelUpload();
        return;//退出函数
    }
}
//addFile函数ok
function addFile() {
    document.getElementsByName("file")[0].click();
}
//readFile函数
function readFile() {
    var uploadFiles = document.getElementsByName("file")[0].files;
    var fileAddress = document.getElementsByClassName("fileAddress")[0];
    let formData = new FormData();
    formData.append('file', uploadFiles[0]);//这里的file要与后台@RequestParam的参数值相对应
    fetch('/upload', {
        method: 'post',
        body: formData,
    }).then(response => response.text()).then(data => {
        if (data.substring(0, 8) != "/upload/") {
            alert(data);
            document.getElementsByName("file")[0].value = "";
        } else {
            fileAddress.value = data;
        }
    }).catch(function (e) {
        alert("error:" + e);
    })
}
window.onload = function () {
    var mdValue = document.getElementById("md-area").value;
    var converter = new showdown.Converter();
    var html = converter.makeHtml(mdValue);
    document.getElementById("show").innerHTML = html;
    var times = document.getElementsByClassName("createTime");
    var timesLength = times.length;
    if(timesLength>0){
        for(var i=0;i<timesLength;i++){
            jsDateDiff(times[i]);
        }
    }
    //这边开始批量转markdown
    var subMdAreaLength = document.getElementsByClassName("comment-content").length;
    for (var i = 0; i < subMdAreaLength; i++) {
        var subMdarea = document.getElementsByClassName("comment-content")[i];
        html = converter.makeHtml(subMdarea.getAttribute("value"));
        subMdarea.innerHTML = html;
    }
    var uploadImage = document.getElementsByName("file")[0];
    uploadImage.addEventListener('change', readFile, false);

    MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
}
function msgonmouseover(i) {
    if (i == 2) {
        document.getElementsByClassName("three-msg-box")[i].style.display = "block";
    } else {
        document.getElementsByClassName("three-msg-box")[i].style.display = "flex";
    }
}
function msgonmouseout(i) {
    if (i != 2) {
        document.getElementsByClassName("three-msg-box")[i].style.display = "none";
    }
}
//跟帖函数
function storey(element) {
    var content = document.getElementById("md-area1").value;
    var invitationId = element.previousElementSibling.value;
    let formData = new FormData();
    formData.append('content', content);
    formData.append('invitationId', invitationId);
    fetch('/storey', {
        method: 'post',
        body: formData,
    }).then(response => response.text()).then(data => {
        if (data == "needLogin") {
            alert("需要登录");
        } else if (data == "success") {
            window.location.reload();
        } else {
            alert(data);
        }
    }).catch(function (e) {
        alert("error:" + e);
        return;
    })
}
//拉出回复框
function showCommentBox(element) {
    var inputBox = element.parentElement.nextElementSibling.firstChild.nextElementSibling;
    var targetUserId = element.previousElementSibling.value;
    inputBox.style.display = "block";
    inputBox.firstChild.nextElementSibling.setAttribute("placeholder", "回复层主");
    // inputBox.firstChild.nextElementSibling.focus();
    inputBox.lastChild.previousElementSibling.previousElementSibling.value = targetUserId;
}
//拉出回复框
function showCommentBoxByUser(element) {
    var targetUserName = element.previousElementSibling.value;
    var targetUserId = element.nextElementSibling.value;
    var inputBox = element.parentElement.parentElement.parentElement.parentElement.firstChild.nextElementSibling;
    inputBox.style.display = "block";
    inputBox.firstChild.nextElementSibling.setAttribute("placeholder", "回复:" + targetUserName);
    // inputBox.firstChild.nextElementSibling.focus();
    inputBox.lastChild.previousElementSibling.previousElementSibling.value = targetUserId;
}
//回复框消失
function removeCommentBox(element) {
    var inputBox = element.parentElement;
    if (element.value == null || element.value == "") {
        inputBox.style.display = "none";
    }
}
//回复函数
function comment(element) {
    var content = element.previousElementSibling.previousElementSibling.value;
    var storeyId = element.previousElementSibling.value;
    var invitationId = element.nextElementSibling.nextElementSibling.value;
    var targetUserId = element.nextElementSibling.value;
    var placeholder = element.previousElementSibling.previousElementSibling.getAttribute("placeholder");
    // console.log(placeholder);
    var targetType;
    if (placeholder == "回复层主") {
        targetType = "storey";
    } else {
        targetType = "comment";
    }

    //表示回复层主
    if (content == "" || content == null) {
        alert("内容不能为空");
        return;
    }
    fetch('/comment?targetUserId=' + targetUserId + '&invitationId=' + invitationId + '&storeyId=' +
        storeyId + '&content=' + content + '&targetType=' + targetType)
        .then(function (res) {
            return res.text();
        })
        .then(function (data) {
            if (data == "needLogin") {
                alert("需要登录");
            } else if (data == "success") {
                window.location.reload();
            } else {
                alert(data);
            }
        }).catch(function (e) {
            alert("error:" + e);
        })
}
//点击like按钮
function like(element) {
    var invitationId = element.previousElementSibling.value;
    //这边用于修改状态
    fetch('/update/invitation/likeStatus?invitationId=' + invitationId)
        .then(function (res) {
            return res.text();
        })
        .then(function (data) {
            if (data == 1) {
                element.style.color = "#fa4d6c";
                element.lastElementChild.innerHTML++;//先加一保证用户体验
            } else if (data == 0) {
                element.style.color = "#afafaf";
                element.lastElementChild.innerHTML--;//先减一保证用户体验
            } else if (data == -2) {
                alert("请先登录");
            } else {
                alert("未知错误");
            }
            //这边用于刷新,保证数据准确
            fetch('/update/invitation/like?invitationId=' + invitationId)
                .then(function (res) {
                    return res.text();
                })
                .then(function (data) {
                    if (data >= 0) {
                        element.lastElementChild.innerHTML = data;
                    } else {
                        alert(data);
                    }
                }).catch(function (e) {
                    alert("error:" + e);
                })
        }).catch(function (e) {
            alert("error:" + e);
        })
}
//点击star(帖子)按钮
function star(element) {
    var invitationId = element.previousElementSibling.previousElementSibling.value;
    //这边用于修改状态
    fetch("/update/target/starStatus?targetType=invitation&targetId=" + invitationId)
        .then(function (res) {
            return res.text();
        })
        .then(function (data) {
            if (data == 1) {
                element.style.color = "#ffc761";
                element.lastElementChild.innerHTML++;
            } else if (data == 0) {
                element.style.color = "#afafaf";
                element.lastElementChild.innerHTML--;
            } else if (data == -2) {
                alert("请先登录");
            } else {
                alert("未知错误");
            }
            //这边用于刷新
            fetch("/update/target/star?targetType=invitation&targetId=" + invitationId)
                .then(function (res) {
                    return res.text();
                })
                .then(function (data) {
                    if (data >= 0) {
                        element.lastElementChild.innerHTML = data;
                    } else {
                        alert(data);
                    }
                }).catch(function (e) {
                    alert("error:" + e);
                })
        }).catch(function (e) {
            alert("error:" + e);
        })
}
//用于关注用户
function starUser(element) {
    var userId = element.previousElementSibling.value;
    //这边用于修改状态
    fetch("/update/target/starStatus?targetType=user&targetId=" + userId)
        .then(function (res) {
            return res.text();
        })
        .then(function (data) {
            if (data == 1) {
                element.style.background = "#ff8d00";
                element.firstElementChild.setAttribute("class", "fa fa-check");
                element.lastElementChild.innerHTML = "已关注";
            } else if (data == 0) {
                element.style.background = "#00d1b2";
                element.firstElementChild.setAttribute("class", "fa fa-star");
                element.lastElementChild.innerHTML = "关注";
            } else if (data == -2) {
                alert("请先登录");
            } else {
                alert("未知错误");
            }
        }).catch(function (e) {
            alert("error:" + e);
        })
}
//点击supportStorey按钮
function supportStorey(element) {
    var invitationId = element.nextElementSibling.value;
    var targetId = element.previousElementSibling.value;
    var targetType = "storey";
    supportFetch(element, targetId, targetType, invitationId);

}
//点击supportUser按钮
function supportComment(element) {
    var invitationId = element.nextElementSibling.value;
    var targetId = element.previousElementSibling.value;
    var targetType = "comment";
    supportFetch(element, targetId, targetType, invitationId);
}
function supportFetch(element, targetId, targetType, invitationId) {
    fetch("/support?targetId=" + targetId + "&targetType=" + targetType + "&invitationId=" + invitationId)
        .then(function (res) {
            return res.text();
        })
        .then(function (data) {
            if (data == "1") {
                element.style.color = "#1b7eb8";
                element.lastElementChild.innerHTML++;
            } else if (data == "0") {
                element.style.color = "#afafaf";
                element.lastElementChild.innerHTML--;
            } else if (data == "needLogin") {
                alert("请先登录");
                return;
            } else {
                alert("未知错误");
                return;
            }
            //这边用于刷新
            fetch("/update/support?" + "targetType=" + targetType + "&targetId=" + targetId)
                .then(function (res) {
                    return res.text();
                })
                .then(function (data) {
                    if (data >= 0) {
                        element.lastElementChild.innerHTML = data;
                    } else {
                        alert(data);
                    }
                }).catch(function (e) {
                    alert("error:" + e);
                })
        }).catch(function (e) {
            alert("error:" + e);
        })
}

//时间显示格式
function jsDateDiff(element){    
    var time = element.innerHTML; 
    var date = time.substring(0,10);
    var d_minutes,d_hours,d_days,d_weeks,d_months,d;
    var timeNow = parseInt(new Date().getTime()/1000);
    pTime_new = new Date(time).getTime()/1000;
    d = timeNow - pTime_new;
    d_months = parseInt(d/60/60/24/30); 
    d_weeks = parseInt(d/60/60/24/7);
    d_days = parseInt(d/60/60/24);       
    d_hours = parseInt(d/60/60);       
    d_minutes = parseInt(d/60);
    if(d_months>0&&d_months<3){
        element.innerHTML = d_months+"个月前"; 
    }else if(d_months<=0&&d_weeks>0){
        element.innerHTML = d_weeks+"周前";
    }else if(d_weeks<=0&&d_days>0){
        element.innerHTML = d_days+"天前";
    }else if(d_days<=0 && d_hours>0){       
        element.innerHTML = d_hours+"小时前";       
    }else if(d_hours<=0 && d_minutes>0){       
        element.innerHTML = d_minutes+"分钟前";       
    }else if(d_months>=3){
        element.innerHTML = date;
    }else{
        element.innerHTML = "刚刚";
    }    
}
